package wicketcool.converter;

import japa.parser.ast.body.MethodDeclaration;
import japa.parser.ast.stmt.BlockStmt;
import japa.parser.ast.stmt.ReturnStmt;
import japa.parser.ast.stmt.Statement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import wicketcool.model.method.WCLMethod;
import wicketcool.model.method.WCLReturnStatement;
import wicketcool.model.method.WCLStatement;

import java.util.ArrayList;
import java.util.List;

/**
 * User: rabbit
 * Date: Aug 3, 2009
 */
@Component
public class DefaultMethodConverter implements MethodConverter {

    @Autowired
    private ModifierConverter modifierConverter;
    @Autowired
    private TypeConverter typeConverter;
    @Autowired
    private ValueConverter valueConverter;

    public MethodDeclaration createMethodDeclaration(WCLMethod method) {

        MethodDeclaration methodDeclaration = new MethodDeclaration(
                modifierConverter.modifierToCUModifierInt(method.getModifier()),
                typeConverter.createType(method.getType()),
                method.getName());

        if (method.hasBody()) {
            List<Statement> statements = createStatements(method.getBody().getStatements());
            BlockStmt blockStmt = new BlockStmt(statements);
            methodDeclaration.setBody(blockStmt);
        }
        return methodDeclaration;
    }

    private List<Statement> createStatements(List<WCLStatement> wclStatements) {

        List<Statement> statements = new ArrayList<Statement>();

        for (WCLStatement wclStatement : wclStatements) {
            if (wclStatement instanceof WCLReturnStatement) {
                WCLReturnStatement returnStatement = (WCLReturnStatement) wclStatement;
                statements.add(new ReturnStmt(valueConverter.createExpression(returnStatement.getValue())));
            }
        }

        return statements;
    }
}
